package com.example.controller;


import com.example.mapper.PostsMapper;
import com.example.pojo.Discuss;
import com.example.pojo.Posts;
import com.example.service.IPostsService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2024-06-12
 */
@RestController
@RequestMapping("/posts")
public class PostsController {
    @Resource
    private IPostsService iPostsService;
    @Resource
    private PostsMapper postsMapper;
    //首页的查看所有论坛和帖子   以及下面有对齐进行分类处理

    @Resource
    private RedisTemplate<String, Posts> redisTemplate;
    @GetMapping("getAll")
    @Cacheable(value = "postsCache", key = "'allPosts'")
    public List<Posts> getAll() {
        // 这里的实际逻辑会被缓存
        return iPostsService.getAll();
    }

    @GetMapping("addPost")
    public void addPost(@RequestParam("uid") Integer uid,@RequestParam("bid") Integer bid,@RequestParam("title") String title,
                        @RequestParam("content") String content,@RequestParam("images") String images){
        iPostsService.addPost(uid,bid,title,content,images);
    }


    //帖子下的评论
    @GetMapping("getDiscuss")
    public List<Discuss> getDiscuss(@RequestParam("pid") Integer pid){
        return iPostsService.getDiscuss(pid);
    }


    @GetMapping("addDiscuss")
    public void addDiscuss(@RequestParam("uid") Integer uid,@RequestParam("text") String text,@RequestParam("pid") Integer pid){
        iPostsService.addDiscuss(uid,text,pid);
    }

    //查询到当前论坛的所有帖子
    @GetMapping("getDiscuss_Bar")
    public List<Posts> getDiscuss_Bar(@RequestParam("bid") Integer bid,@RequestParam("uid") Integer uid){
        return iPostsService.getDiscuss_Bar(bid,uid);
    }


    @GetMapping("getDiscuss_User")
    public List<Posts> getDiscuss_User(@RequestParam("uid") Integer uid){
        return iPostsService.getDiscuss_User(uid);
    }

    @GetMapping("findPostByPid")
    public Posts findPostByPid(@RequestParam("pid") Integer pid){
        return postsMapper.findPostByPid(pid);
    }
//这个是浏览记录
@GetMapping("findpbu")
public List<Posts> findPostByPidUid(@RequestParam("pid") Integer pid, @RequestParam("uid") Integer uid) {
    String redisKey = "history_uid";

    // 根据pid从数据库中查询post对象
    Posts newPost = postsMapper.findPostByPid(pid);

    // 设置otherid和初始sc值
    newPost.setOtherid(uid);

    // 从Redis中获取所有浏览记录，并转换成List返回
    Set<Posts> postsSet = redisTemplate.opsForZSet().range(redisKey, 0, -1);
    List<Posts> postsList = new ArrayList<>(postsSet);

    // 检查是否已存在相同pid和uid的帖子记录
    Optional<Posts> existingPost = postsList.stream()
            .filter(post -> pid.equals(post.getPid()) && uid.equals(post.getOtherid()))
            .findFirst();

    if (existingPost.isPresent()) {
        // 如果已存在相同的记录，则保留已有的sc值
        newPost.setSc(existingPost.get().getSc());
    } else {
        // 否则设置默认的sc值（这里默认设置为0，可以根据实际需求修改）
        newPost.setSc(0);
    }

    // 设置该键的过期时间为20天，即 20 * 24 * 60 * 60 秒
    redisTemplate.expire(redisKey, 20, TimeUnit.DAYS);

    // 将新的post对象添加到Redis的有序集合中，score使用当前时间戳
    redisTemplate.opsForZSet().add(redisKey, newPost, System.currentTimeMillis());
// 倒序排列
    Collections.reverse(postsList);
    // 返回最新的postsList
    return postsList;
}


    @GetMapping("history")
    public List<Posts> findPostByPidUid( @RequestParam("uid") Integer uid){
        String redisKey = "history_uid";
        //从redis中获取所有浏览记录
        Set<Posts> postsSet = redisTemplate.opsForZSet().range(redisKey,0,-1);
        List<Posts> postsList = new ArrayList<>(postsSet);
// 筛选出otherid等于uid的Posts对象
        List<Posts> filteredPosts = postsList.stream()
                .filter(post -> uid.equals(post.getOtherid()))
                .collect(Collectors.toList());
// 倒序排列
        Collections.reverse(filteredPosts);
        return  filteredPosts;
    }

    @GetMapping("moveHistory")
    public void moveHistory(@RequestParam("uid") Integer uid, @RequestParam("pid") Integer pid) {
        String redisKey = "history_uid";
        // 从 Redis 中获取所有浏览记录
        Set<Posts> postsSet = redisTemplate.opsForZSet().range(redisKey, 0, -1);
        List<Posts> postsList = new ArrayList<>(postsSet);

        // 删除符合条件的 Posts 对象
        postsList.removeIf(post -> uid.equals(post.getOtherid()) && pid.equals(post.getPid()));

        // 更新 Redis 中的有序集合
        if (postsList.isEmpty()) {
            // 如果 postsList 为空，直接设置 Redis 中的有序集合为空
            redisTemplate.delete(redisKey);
        } else {
            // 否则，执行删除操作
            redisTemplate.opsForZSet().remove(redisKey, postsList.toArray());
        }
    }


    @GetMapping("belike")
    public List<Posts> belike(@RequestParam("uid") Integer uid,
                              @RequestParam("sc") Integer sc,
                              @RequestParam("pid") Integer pid) {
        String redisKey = "history_uid";
        Set<Posts> postsSet = redisTemplate.opsForZSet().range(redisKey, 0, -1);
        List<Posts> postsList = new ArrayList<>(postsSet);

        if (postsList != null) {
            // 根据 uid 和 pid 查找对应的帖子
            Optional<Posts> optionalPost = postsList.stream()
                    .filter(post -> uid.equals(post.getOtherid()) && pid.equals(post.getPid()))
                    .findFirst();

            if (optionalPost.isPresent()) {
                Posts post = optionalPost.get();

                // 如果请求将 sc 设置为 1
                if (sc == 1 && post.getSc() == 0) {
                    // 删除之前标记为收藏的相同 uid 和 pid 的帖子
                    postsList.removeIf(p -> uid.equals(p.getOtherid()) && p.getPid().equals(pid) && p.getSc() == 1);
                    post.setSc(1);
                } else if (sc == 0 && post.getSc() == 1) {
                    // 如果请求将 sc 设置为 0
                    // 删除之前标记为未收藏的相同 uid 和 pid 的帖子
                    postsList.removeIf(p -> uid.equals(p.getOtherid()) && p.getPid().equals(pid) && p.getSc() == 0);
                    post.setSc(0);
                }

                // 更新 Redis 中的有序集合
                redisTemplate.delete(redisKey);  // 先删除旧的有序集合

                if (!postsList.isEmpty()) {
                    // 如果 postsList 不为空，重新添加更新后的帖子
                    postsList.forEach(p -> redisTemplate.opsForZSet().add(redisKey, p, p.getScore()));
                }
            }
        }

        // 根据 uid 和 sc 过滤并倒序排列
        List<Posts> filteredPosts = postsList.stream()
                .filter(post -> uid.equals(post.getOtherid()) && sc.equals(post.getSc()))
                .sorted(Comparator.comparing(Posts::getScore).reversed()) // 根据 score 倒序排列
                .collect(Collectors.toList());
// 倒序排列
        Collections.reverse(filteredPosts);
        return filteredPosts;
    }





    @GetMapping("getDiscuss_Pid")
    public Posts getDiscuss_Pid(@RequestParam("pid") Integer pid){
        return iPostsService.getDiscuss_Pid(pid);
    }

    @GetMapping("delPosts")
    public void delPosts(@RequestParam("pid") Integer pid){
        postsMapper.deleteById(pid);
    }

    @GetMapping("delDis")
    public void delDis(@RequestParam("cid") Integer cid){
        postsMapper.delDis(cid);
    }

    @GetMapping("getAllDis")
    public Integer getAllDis(){
        return postsMapper.getAllDis();
    }
}

